package com.utils.basejava.NIO;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Scanner;

public class TestNonBlockingNIOUDP {
	
	
	public void send() throws IOException {
		DatagramChannel dc = DatagramChannel.open();
		dc.configureBlocking(false);
		ByteBuffer bb = ByteBuffer.allocate(1024);
		@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
		
		while(sc.hasNext()) {
			bb.put(sc.next().getBytes());
			bb.flip();
			dc.send(bb, new InetSocketAddress("127.0.0.1", 9898));
			bb.clear();
		}
		dc.close();
	}
	
	
	public void receiver() throws IOException {
		DatagramChannel dc = DatagramChannel.open();
		dc.configureBlocking(false);
		dc.bind(new InetSocketAddress(9898));
		
		Selector selector = Selector.open();
		dc.register(selector, SelectionKey.OP_READ);
		
		while(selector.select()>0) {
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			while(iterator.hasNext()) {
				SelectionKey sk = iterator.next();
				if(sk.isReadable()) {
					ByteBuffer bb = ByteBuffer.allocate(1024);
					dc.receive(bb);
					bb.flip();
					System.out.println(new String(bb.array(),0,bb.limit()));
					bb.clear();
				}
				iterator.remove();				
			}
		}
		
	}

}
